package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.CommentManager;
import com.xyzh05.model.Comment;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class CommentAction extends BaseAction implements Preparable {
    private CommentManager commentManager;
    private List comments;
    private Comment comment;
    private Long id;
    private String query;

    public void setCommentManager(CommentManager commentManager) {
        this.commentManager = commentManager;
    }

    public List getComments() {
        return comments;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String commentId = getRequest().getParameter("comment.id");
            if (commentId != null && !commentId.equals("")) {
                comment = commentManager.get(new Long(commentId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        comments = commentManager.search(query, Comment.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public String delete() {
        commentManager.remove(comment.getId());
        saveMessage(getText("comment.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            comment = commentManager.get(id);
        } else {
            comment = new Comment();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (comment.getId() == null);

        commentManager.save(comment);

        String key = (isNew) ? "comment.added" : "comment.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}